package com.moon.service;

import com.moon.dao.*;
import com.moon.dto.TUser;
import com.moon.entity.*;
import com.moon.es.EsDataWriter;
import com.moon.es.EsProductRepository;
import com.moon.feign.UserFeign;
import com.moon.utils.IdWorker;
import com.moon.utils.RedisLock;
import com.moon.utils.UserUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class OrderService {

//    @Autowired
//    private TOrderMapper tOrderMapper;
//
//    @Autowired
//    TAuctionMapper auctionMapper;
//
//    @Autowired
//    RabbitTemplate rabbitTemplate;
//
//    @Autowired
//    TProductMapper productMapper;


    @Autowired
    EsProductRepository esProductRepository;


    @Autowired
    @Qualifier("idWorker1")
    private IdWorker idWorker1;

    @Autowired
    @Qualifier("esProduct")
    EsDataWriter esDataWriter;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    ProductService productService;

    @Autowired
    private TOrderMapper tOrderMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

//    @Transactional
    public String addOrder(TAuction auction) {
        System.out.println("进入addOrder方法");
        Long productId = auction.getProductId();
        Long sellerId1 = productService.selectSellerIdByProductId(productId);

//        com.moon.entity.TUser user = UserUtils.getCurrUserFromHeader("token", com.moon.entity.TUser.class, request);

        //生成订单
        TOrder order = new TOrder();
        order.setId(idWorker1.nextId());
        order.setAuctionId(auction.getId());
        order.setSellerId(sellerId1);
        order.setBuyerId(auction.getBuyerId());
        order.setOrderPrice(auction.getTopPrice());
        order.setExtraPrice(auction.getTopPrice().multiply(new BigDecimal(0.03)));
        order.setFinalPrice(auction.getTopPrice().subtract(auction.getSecurityPrice()));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(0);
        tOrderMapper.insert(order);
        Map<String, Object> map = new HashMap<>();
        String userEmail=userFeign.getemail(order.getBuyerId());
        Long sellerId = order.getSellerId();
        String sellerEmail=userFeign.getemail(sellerId);
        map.put("userEmail", userEmail);
        map.put("sellerEmail", sellerEmail);
        //通知买家和卖家
        rabbitTemplate.convertAndSend("fanoutExchange", null, map);

        return "success";
    }


}
